from flask import jsonify, request
from ..models.staff import Staff
from ..extensions import db
from ..utils.response import pagination, error, success
from datetime import datetime

# 创建服务人员
def create_staff():
    try:
        data = request.json
        print(data)
        
        # 验证必填字段
        if not data.get('name'):
            return error('姓名为必填字段',400)
        
        # 验证工龄必须为非负数
        work_years = data.get('work_years', 0)
        if work_years < 0:
            return error('工龄必须为非负数',400)
        
        # 验证性别必须为M或F
        gender = data.get('gender')
        if gender and gender not in ['M', 'F']:
            return error('性别必须为M（男）或F（女）',400)  
        
        # 创建服务人员实例
        staff = Staff(
            name=data['name'],
            work_years=work_years,
            gender=gender,
            job_type=data.get('job_type'),
            is_on_duty=data.get('is_on_duty')
        )
        
        db.session.add(staff)
        db.session.commit()
        
        return success('服务人员创建成功', staff.to_dict())
    except Exception as e:
        print(e)
        db.session.rollback()
        return error('服务人员创建失败', 500)

# 获取服务人员列表
def get_staffs(data):
    """获取服务人员列表，支持按工种和在岗状态筛选，支持分页"""
    try:
        # 支持按工种和在岗状态筛选
        job_type = data.get('job_type')
        is_on_duty = data.get('is_on_duty')
        
        query = Staff.query
        
        if job_type:
            query = query.filter_by(job_type=job_type)
        
        if is_on_duty is not None:
            # 转换为布尔值
            query = query.filter_by(is_on_duty=str(is_on_duty).lower() == 'true')
        
        # 计算总数
        total = query.count()
        
        # 按创建时间倒序排列
        query = query.order_by(Staff.created_at.desc())
        
        # 获取分页参数
        page = int(data.get('page', 1))
        page_size = int(data.get('page_size', 10))
        
        # 处理无效的分页参数
        if page < 1:
            page = 1
        if page_size < 1:
            page_size = 10
        elif page_size > 100:
            page_size = 100  # 限制最大每页记录数
        
        # 计算偏移量
        offset = (page - 1) * page_size
        
        # 获取分页数据
        staffs = query.offset(offset).limit(page_size).all()
        
        # 返回分页数据
        return pagination(
            items=[staff.to_dict() for staff in staffs],
            total=total,
            msg='获取成功',
            code=200
        )
    except Exception as e:
        return error('获取失败', 500)

# 更新服务人员信息
def update_staff():
    try:
        data = request.json
        staff_id = data.get('id')
        
        if not staff_id:
            return error('未提供服务人员ID',400)
        
        staff = Staff.query.get(staff_id)
        
        if not staff:
            return error('服务人员不存在',404)
        
        # 更新字段
        if 'name' in data:
            staff.name = data['name']
        
        if 'work_years' in data:
            if int(data['work_years']) < 0:
                return error('工龄必须为非负数',400)
            staff.work_years = int(data['work_years'])
        
        if 'gender' in data:
            if data['gender'] and data['gender'] not in ['M', 'F']:
                return error('性别必须为M（男）或F（女）',400)
            staff.gender = data['gender']
        
        if 'job_type' in data:
            staff.job_type = data['job_type']
        
        if 'is_on_duty' in data:
            staff.is_on_duty = bool(data['is_on_duty'])
        
        db.session.commit()
        
        return success('服务人员信息更新成功', staff.to_dict())
    except Exception as e:
        print(e)
        db.session.rollback()
        return error('服务人员信息更新失败', 500)

# 删除服务人员
def delete_staff():
    try:
        data = request.json
        staff_id = data.get('id')
        
        if not staff_id:
            return error('未提供服务人员ID',400)
        
        staff = Staff.query.get(staff_id)
        
        if not staff:
            return error('服务人员不存在',404)
        
        db.session.delete(staff)
        db.session.commit()
        
        return success('服务人员删除成功')
    except Exception as e:
        db.session.rollback()
        return error('服务人员删除失败', 500)

# 批量更新服务人员在岗状态
def batch_update_duty_status():
    try:
        data = request.json
        staff_ids = data.get('staff_ids')
        is_on_duty = data.get('is_on_duty')
        
        if not staff_ids or not isinstance(staff_ids, list):
            return error('必须提供服务人员ID列表',400)
        
        if is_on_duty is None:
            return error('必须指定在岗状态',400)
        
        # 批量更新在岗状态
        updated_count = Staff.query.filter(Staff.id.in_(staff_ids)).update(
            {'is_on_duty': bool(is_on_duty)},
            synchronize_session=False
        )
        
        db.session.commit()
        
        if updated_count == 0:
            return error('未找到匹配的服务人员',404)
        
        return success(f'成功更新 {updated_count} 名服务人员的在岗状态', {
            'updated_count': updated_count
        })
    except Exception as e:
        db.session.rollback()
        return error('批量更新在岗状态失败', 500)
